package com.vf.cloud.paas.common.security.aop;

import lombok.RequiredArgsConstructor;

import java.util.concurrent.TimeUnit;

import javax.servlet.http.HttpServletRequest;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import com.jfinal.kit.StrKit;
import com.vf.cloud.paas.common.service.IRedis;
import com.vf.cloud.paas.common.util.JWTUtil;
import com.vf.cloud.paas.common.util.R;
import com.vf.cloud.paas.common.util.WebUtils;

@RequiredArgsConstructor
@Aspect
@Component
public class TokenRequiredAop {

	private final IRedis redisImpl;

	@Pointcut("@annotation(com.vf.cloud.paas.common.security.annotation.TokenRequired)")
	private void pointcut() {
	}

	@Around("pointcut()")
	public Object doAround(ProceedingJoinPoint joinPoint) throws Throwable {
		ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
		assert attributes != null;
		HttpServletRequest request = attributes.getRequest();
		String token = WebUtils.getToken(request);
		if (StrKit.isBlank(token)) {
			return R.expired();
		}
		long expire = redisImpl.getExpire(token, TimeUnit.MILLISECONDS);
		if (expire < 0) {
			redisImpl.delete(token);
			return R.expired();
		}

		try {
			String userId = JWTUtil.getClainByName(token, "userId").asString();
			request.setAttribute("currentUserId", userId);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return joinPoint.proceed();
	}

}
